package com.wy.tingshu.servlet.tarck;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wy.tingshu.data_object.TrackDO;
import com.wy.tingshu.repository.TrackRepo;
import com.wy.tingshu.util.Log;
import com.wy.tingshu.view_object.UserVO;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.HashMap;

/**
 * 录制好的音频上传到后台后台接收
 **/
@WebServlet("/studio/track/record.json")
public class RecordJsonServlet extends HttpServlet {
    private final ObjectMapper objectMapper=new ObjectMapper();
    private final TrackRepo trackRepo=new TrackRepo();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        String title = req.getParameter("title");
        String type = req.getHeader("Content-Type");
        Log.println("title:"+title);
        Log.println("type:"+type);

        //获取uid
        UserVO currentUser=null;
        HttpSession session = req.getSession(false);
        if(session!=null){
            currentUser= (UserVO) session.getAttribute("currentUser");
        }
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("application/json");
        PrintWriter writer= resp.getWriter();
        if(currentUser==null){//cookie为空
            Log.println("用户未登录");
            //上传失败
            HashMap<String,Boolean> result=new HashMap<>();
            result.put("result",false);
            String json = objectMapper.writeValueAsString(result);
            Log.println(json);
            writer.println(json);//打印到浏览器上
            return;
        }
        trackRepo.insert(currentUser.uid,title,type, req.getInputStream());//音频对应数据插入音频表
        Log.println("将数据保存到数据库表中");
        HashMap<String,Boolean> result=new HashMap<>();
        result.put("result",true);
        String json = objectMapper.writeValueAsString(result);
        Log.println(json);
        writer.println(json);

        resp.sendRedirect("/studio");

        //完整的音频数据放在inputStream（is）中
//        ServletInputStream is=req.getInputStream();
//        //把数据写在本地
//        try (OutputStream os=new FileOutputStream("D:\\Users\\Dell\\Music\\"+title)){
//            byte[] buf=new byte[4096];
//            while (true){
//                int n=is.read(buf);
//                if(n==-1){
//                    break;
//                }
//                os.write(buf,0,n);
//            }
//            os.flush();
//        }

    }
}
